<script setup>
import { onMounted, ref  } from 'vue';
import axios from 'axios';
import BookList from "@/components/BookList.vue";
import {Document, Notebook} from "@element-plus/icons-vue";


const typeList = ref([]);
const initBookType = async () => {
  try {
    const resp = await axios.get('/bookType/findAll');
    typeList.value = resp.data; // 获取响应数据
  } catch (error) {
    console.error('Error fetching book types:', error);
  }
}

const topPage = ref({});
const param = ref({
  pageNum: 1,
  pageSize: 12,
});
const initTop = async () => {
  const resp = await axios.post('/book/top', param.value);
  topPage.value = resp.data;
};


const handleCurrentPage = (val) => {
  param.value.pageNum = val;
  initTop();
};

const handleTypeCurrentPage = (val) => {
  param.value.pageNum = val;
  findByType();
};

const typePage = ref([]);
const findByType = async ()=>{
  console.log(param.value)
  const resp = await axios.post('/book/findByType', param.value);
  typePage.value = resp.data
}

const activeName = ref("hotSelling");
const handleTabChange = (tab)=>{
  const typeId = tab.props.name;
  param.value.pageNum = 1;
  if(typeId === "hotSelling"){
    initTop();
  }else{
    param.value.typeId = typeId;
    findByType();
  }

}

onMounted(() => {
  initBookType();
  initTop();
})

</script>

<template>
  <div>

    <el-tabs type="border-card"
             @tab-click="handleTabChange"
             v-model="activeName">

      <el-tab-pane name="hotSelling">
        <template #label>
          <el-icon><Document /></el-icon>热销榜
        </template>
        <book-list :book-list="topPage.records"
                   :current-page="param.pageNum"
                   :page-size="param.pageSize"
                   :total-items="topPage.total"
                   @change-page="handleCurrentPage">
        </book-list>
      </el-tab-pane>

      <el-tab-pane v-for="type in typeList"
                   :key="type.id"
                   :label="type.name"
                   :name="String(type.id)">
        <template #label>
          <el-icon><Notebook /></el-icon>{{ type.name }}
        </template>
        <book-list :book-list="typePage.records"
                   :current-page="param.pageNum"
                   :page-size="param.pageSize"
                   :total-items="typePage.total"
                   @change-page="handleTypeCurrentPage">
        </book-list>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>

</style>